import {getSysMenuNav} from '$my/code/api/sys-menu'
import {isURL} from '@/utils/validate'


const _import = require('../router/' + process.env.NODE_ENV)

export function dynamicRouter($router) {
  return new Promise(resolve => {
    getSysMenuNav().then(res => {
      const menuList = res.menuList || []
      clearOldDynamicRoutes($router)
      fnAddDynamicMenuRoutes(menuList, [], $router)
      $router.options.isAddDynamicMenuRoutes = true
      // const permissions = res.permissions || []
      setTimeout(() => {
        resolve()
      }, 100)
    })
  })
}


/**
 * 清除旧的动态生成的router
 * @param $router
 */
function clearOldDynamicRoutes($router) {
  console.info($router.matcher)
  // 没有想到清除路由的好办法
  // const staticRoute = []
  // const routes = $router.getRoutes()
  // routes.forEach(route => {
  //   if(!route.meta.isDynamic) {
  //     staticRoute.push(route)
  //   }
  // })
  // $router.matcher = new Router({
  //   routes,
  //   ...globalConfig.router
  // }).matcher
}

/**
 * 根据菜单生成动态路由
 * @param menuList
 * @param routes
 * @param $router
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = [], $router) {
  let temp = []
  for (let i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list)
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '')

      const route = {
        path: menuList[i].url,
        component: null,
        name: menuList[i].url,
        meta: {
          menuId: menuList[i].menuId,
          tab: menuList[i].name,
          isDynamic: true,
          isTab: true,
          icon: menuList[i].icon || '',
          iframeUrl: ''
        }
      }
      // url以http[s]://开头, 通过iframe展示
      if (isURL(menuList[i].url)) {
        route.path = `i-${menuList[i].menuId}`
        route.name = `i-${menuList[i].menuId}`
        route.meta.iframeUrl = menuList[i].url
      } else if(menuList[i].url) {
        try {
          route.component = _import(`modules/${menuList[i].url}`) || null
        } catch (e) {
          console.error(e)
        }
      }
      if(route.component !== null) {
        routes.push(route)
        $router.addRoute('main', route)
      }
    }
  }
  if (temp.length >= 1) {
      fnAddDynamicMenuRoutes(temp, routes, $router)
  } else {
    const others = {path: '*', component: _import('_404'), name: '404', meta: {title: '404未找到'}}
    console.info($router.addRoute)
    $router.addRoute(others)
    console.log('\n')
    console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
    console.log(routes)
    console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
  }
}


export function dynamicMenu(menuList) {
  const menus = []
  menuList.forEach(item => {
    const menu = {
      text: item.name,
      icon: item.icon,
      index: '/main/' + (item.url)
    }

    if (item.list && item.list.length > 0) {
      menu.children = dynamicMenu(item.list)
    }
    menus.push(menu)
  })
  return menus
}
